function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import { DagreLayout } from '@antv/layout';
import { NODE_WIDTH, RANK_SEP, NODE_SEP, ConditionTypeEnum, NODE_TYPE_START, NODE_TYPE_END } from "../constant";
// import dagre from '@dagrejs/dagre';
// import ELK from 'elkjs/lib/elk.bundled.js';
// import cytoscape from 'cytoscape';
// import cyDagre from 'cytoscape-dagre';
// import cyElk from 'cytoscape-elk';
// import cyKlay from 'cytoscape-klay';

// cytoscape.use( cyDagre );
// cytoscape.use( cyElk );
// cytoscape.use( cyKlay );

var rankdir = 'LR';
var align = undefined;
var nodeSize = NODE_WIDTH;
var ranksep = RANK_SEP;
var nodesep = NODE_SEP;
var controlPoints = false;
var begin = [40, 40];
export var forceLayout = function forceLayout(flowGraph) {
  var cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  antvDagreLayout(flowGraph, cfg);

  // dagreLayout(flowGraph, cfg);
};

/**
 * 使用AntV的图布局包实现布局
 * @param flowGraph 图实例
 * @param cfg 配置
 */
function antvDagreLayout(flowGraph) {
  var cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var dagreLayout = new DagreLayout({
    begin: begin,
    type: 'dagre',
    rankdir: rankdir,
    align: align,
    nodeSize: nodeSize,
    ranksep: ranksep,
    nodesep: nodesep,
    controlPoints: controlPoints
  });
  dagreLayout.updateCfg(_objectSpread({}, cfg));
  var _dagreLayout$layout = dagreLayout.layout({
      // @ts-ignore
      nodes: flowGraph.getNodes().map(function (node) {
        node.setZIndex(1);
        return node.toJSON();
      }),
      // @ts-ignore
      edges: flowGraph.getEdges().map(function (edge) {
        edge.setZIndex(0);
        return edge.toJSON();
      })
    }),
    newNodes = _dagreLayout$layout.nodes;
  newNodes === null || newNodes === void 0 || newNodes.forEach(function (node) {
    var cell = flowGraph.getCellById(node.id);
    if (cell) {
      cell.position(node.x, node.y);
    }
  });
  // alignNodesVertically(flowGraph);  // 注释掉:这个函数会强制将所有节点对齐到同一水平线,导致分支/并行节点重叠
  fineTuneLayer(flowGraph);

  // fineTuneCatchNodes(flowGraph);
}

/**
 * 垂直对齐同一层的节点，使其中心点对齐
 * @param flowGraph 图实例
 */
function alignNodesVertically(flowGraph) {
  console.log('[alignNodesVertically] Starting vertical alignment');
  
  // 获取所有节点
  var allNodes = flowGraph.getNodes();
  if (allNodes.length === 0) return;
  
  // 找到开始节点作为基准
  var startNode = allNodes.find(function(node) {
    return node.shape === NODE_TYPE_START;
  });
  
  if (!startNode) {
    console.log('[alignNodesVertically] No start node found, using first node');
    startNode = allNodes[0];
  }
  
  var _startNode$position = startNode.position(),
    startY = _startNode$position.y;
  var _startNode$size = startNode.size(),
    startHeight = _startNode$size.height;
  var baseCenterY = startY + startHeight / 2;
  
  console.log('[alignNodesVertically] Using start node as baseline, center Y:', baseCenterY, 'height:', startHeight);
  
  // 将所有节点对齐到基准中心Y
  allNodes.forEach(function(node) {
    var _node$position = node.position(),
      x = _node$position.x,
      oldY = _node$position.y;
    var _node$size = node.size(),
      height = _node$size.height;
    var newY = baseCenterY - height / 2;
    
    console.log('[alignNodesVertically] Node', node.shape, 'height:', height, 'old Y:', oldY, 'new Y:', newY);
    node.position(x, newY);
  });
}

/**
 * 解决Dagre布局部分节点层次过低问题
 * @param flowGraph 图实例
 */
function fineTuneLayer(flowGraph) {
  var queue = flowGraph.getRootNodes();
  var layer = 0;
  // const visited: KeyValue<boolean> = {};
  var _loop = function _loop() {
    var cells = [];
    queue.forEach(function (next) {
      // if (next === null || visited[next.id]) {
      //   return;
      // }
      // visited[next.id] = true;
      var _next$position = next.position(),
        y = _next$position.y;
      next.position(begin[0] + layer * (ranksep + nodeSize + 40), y);
      var neighbors = flowGraph.getNeighbors(next, {
        outgoing: true
      });
      cells = cells.concat(neighbors);
    });
    layer++;
    queue = cells;
  };
  while (queue.length) {
    _loop();
  }
}

/**
 * 调整捕获异常节点/CATCH的布局
 * @param flowGraph 图实例
 */
function fineTuneCatchNodes(flowGraph) {
  var queue = flowGraph.getRootNodes();
  var _loop2 = function _loop2() {
    var cells = [];
    queue.forEach(function (next) {
      var _next$getData = next.getData(),
        model = _next$getData.model;
      var currentModel = model.proxy || model;
      if (currentModel.type === ConditionTypeEnum.CATCH) {
        if (next.shape === ConditionTypeEnum.CATCH) {
          // CATCH start
          beforeCatchStart(flowGraph, next);
        } else {
          // CATCH end
          afterCatchEnd(flowGraph, next);
        }
      }
      var neighbors = flowGraph.getNeighbors(next, {
        outgoing: true
      });
      cells = cells.concat(neighbors);
    });
    queue = cells;
  };
  while (queue.length) {
    _loop2();
  }
}
function beforeCatchStart(flowGraph, catchStart) {
  var catchRootNode = flowGraph.getNeighbors(catchStart, {
    outgoing: true
  })[0];
  var deltaY = catchStart.position().y - catchRootNode.position().y;
  if (!deltaY) return;
  var queue = [catchStart];
  var _loop3 = function _loop3() {
    var cells = [];
    queue.forEach(function (next) {
      var _next$position2 = next.position(),
        x = _next$position2.x,
        y = _next$position2.y;
      next.position(x, y - deltaY);
      var neighbors = flowGraph.getNeighbors(next, {
        incoming: true
      });
      cells = cells.concat(neighbors);
    });
    queue = cells;
  };
  while (queue.length) {
    _loop3();
  }
}
function afterCatchEnd(flowGraph, catchEnd) {
  var catchRootNode = flowGraph.getNeighbors(catchEnd, {
    incoming: true
  })[0];
  var deltaY = catchEnd.position().y - catchRootNode.position().y;
  if (!deltaY) return;
  var queue = [catchEnd];
  var _loop4 = function _loop4() {
    var cells = [];
    queue.forEach(function (next) {
      var _next$position3 = next.position(),
        x = _next$position3.x,
        y = _next$position3.y;
      next.position(x, y - deltaY);
      var neighbors = flowGraph.getNeighbors(next, {
        outgoing: true
      });
      cells = cells.concat(neighbors);
    });
    queue = cells;
  };
  while (queue.length) {
    _loop4();
  }
}
function getNodeOrderFrom(flowGraph) {
  var nodeOrder = [];
  var rootNodes = flowGraph.getRootNodes() || [];
  if (rootNodes) {
    var queue = _toConsumableArray(rootNodes);
    var visited = {};
    var _loop5 = function _loop5() {
      var next = queue.pop();
      if (next == null || visited[next.id]) {
        return 1; // continue
      }
      visited[next.id] = true;
      nodeOrder.push(next.id);
      var neighbors = flowGraph.getNeighbors(next, {
        outgoing: true
      });
      neighbors.sort(function (a, b) {
        var _a$position = a.position(),
          aY = _a$position.y;
        var _b$position = b.position(),
          bY = _b$position.y;
        return aY - bY;
      });
      var lastIndex = queue.length;
      neighbors.forEach(function (neighbor) {
        queue.splice(lastIndex, 0, neighbor);
      });
    };
    while (queue.length > 0) {
      if (_loop5()) continue;
    }
  }
  return nodeOrder;
}

/**
 * 使用Dagre原始包实现布局
 * @param flowGraph 图实例
 * @param cfg 配置
 */
// function dagreLayout(flowGraph: Graph, cfg: any = {}): void {
//   const g = new dagre.graphlib.Graph();
//   g.setGraph({ rankdir, nodesep: 50, ranksep: 50 });
//   g.setDefaultEdgeLabel(() => ({}));

//   flowGraph.getNodes().forEach((node) => {
//     node.setZIndex(1);
//     g.setNode(node.id, { width: nodeSize, height: nodeSize });
//   })

//   flowGraph.getEdges().forEach((edge) => {
//     edge.setZIndex(0);
//     const source = edge.getSourceNode() as Node;
//     const target = edge.getTargetNode() as Node;
//     g.setEdge(source?.id, target?.id);
//   })

//   dagre.layout(g);

//   flowGraph.freeze();

//   g.nodes().forEach((id) => {
//     const node = flowGraph.getCellById(id) as Node;
//     if (node) {
//       const pos = g.node(id);
//       node.position(pos.x, pos.y);
//     }
//   })

//   flowGraph.unfreeze();
// }

/**
 * 使用ELK实现布局
 * @param flowGraph 图实例
 * @param cfg 配置
 */
// function elkLayout(flowGraph: Graph, cfg: any = {}) {
//   const elk = new ELK();
//   const elkOptions: Record<string, any> = {
//     'elk.algorithm': 'layered',
//     'elk.layered.spacing.nodeNodeBetweenLayers': 80,
//     'elk.spacing.nodeNode': 20,
//     'elk.direction': 'RIGHT',
//   };
//   const nodes = flowGraph
//     .getCells()
//     .filter((cell) => cell.isNode())
//     .map((cell) => cell.toJSON()) as any[];
//   const edges = flowGraph
//     .getCells()
//     .filter((cell) => cell.isEdge())
//     .map((cell) => cell.toJSON()) as any[];
//   const elkGraph = {
//     id: 'root',
//     layoutOptions: elkOptions,
//     children: nodes.map((node) => ({
//       ...node,
//       width: nodeSize,
//       height: nodeSize,
//     })),
//     edges: edges.map((edge) => ({
//       ...edge,
//       source: edge.source.cell,
//       target: edge.target.cell,
//     })),
//   };
//   elk
//     .layout(elkGraph as any)
//     .then((layoutedGraph: any) => {
//       flowGraph.freeze();
//       layoutedGraph.children.forEach((node: any) => {
//         const current: Node | undefined = flowGraph.getCellById(node?.id) as Node | undefined;
//         if (current) {
//           current.position(node.x, node.y);
//         }
//       });
//       flowGraph.unfreeze();
//     })
//     .catch(console.error);
// }